package qdu.rg05.test_music_srv;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import java.io.IOException;


public class Srv_2 extends Service {
    MediaPlayer mp;
    Boolean LOOP_FLAG = true;
    class Mybinder extends Binder {
        public void getService(){
            Log.i("mytag", "bind service provided.....");
        }

        public void music_start(){
            if(mp != null)
                mp.start();
        }
        public void music_stop(){
            if(mp != null) {
                mp.stop();
                try {
                    mp.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        public void start_or_pause(){
            if(mp!=null)
                if(mp.isPlaying())
                    mp.pause();
                else{
                    mp.start();
                    Log.i("mytag","music will start or resume");
                }
        }
        public void music_pause(){
            if(mp!=null && mp.isPlaying())
                mp.pause();
        }

        public void set_looping(){
            if(LOOP_FLAG){
                LOOP_FLAG = false;
                mp.setLooping(LOOP_FLAG);
            }
            else{
                LOOP_FLAG = true;
                mp.setLooping(LOOP_FLAG);
            }
        }

        public boolean get_looping(){
            return LOOP_FLAG;
        }
    }
    @Override
    public void onCreate() {
        super.onCreate();
        mp = MediaPlayer.create(this,R.raw.main);//创建媒体对象（媒体对应的当前上下文，媒体数据资源访问）
        mp.setLooping(LOOP_FLAG);
        Log.i("mytag","srv2 oncreate");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("mytag","srv2 onDestory");
        if(mp != null)
            mp.release();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i("mytag","srv2 onbind");
        return new Mybinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i("mytag","srv2 unbind");
        if(mp!=null)
            mp.stop();
        return super.onUnbind(intent);
    }
}
